package com.xu.base.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * json工具类
 *
 * @Author: 许乾伟
 * @Date: 2024/12/23 9:44
 */
public class JsonUtils {
    /**
     * 压缩json数据
     * @param data json字符串
     * @return
     */
    public static String compress(String data) throws IOException {
        if (StringUtils.hasText(data)) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        gzip = new GZIPOutputStream(out);
        gzip.write(data.getBytes("UTF-8"));
        gzip.close();
        return Base64.encodeBase64String(out.toByteArray());
    }

    /**
     * 解压缩json数据
     * @param compressedData 被压缩的json数据
     * @return
     * @throws IOException
     */
    public static String decompress(String compressedData) throws IOException {
        if (StringUtils.hasText(compressedData)) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(Base64.decodeBase64(compressedData));
        GZIPInputStream gzip;
        try {
            gzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzip.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            gzip.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toString("UTF-8");
    }
}
